package com.pomelo.base.core.util;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;

import org.springframework.stereotype.Component;

/**
 * spring工具类
 *
 * @author biankudingcha
 * @date: 2021-07-23
 * @since 0.5.0
 */
@Component
@Lazy(false)
public class SpringUtil implements ApplicationContextAware {

    /**
     * spring容器
     */
    private static ApplicationContext ac = null;

    /**
     * 获取spring容器
     *
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return SpringUtil.ac;
    }

    /**
     * 设置spring容器
     */
    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        SpringUtil.ac = ac;
    }

    /**
     * 获取容器配置的Bean对象
     *
     * @param <T> T
     * @param clazz class
     * @return T
     */
    public static <T> T getBean(Class<T> clazz) {
        return ac.getBean(clazz);
    }

    /**
     * 根据类型和beanId名称获取bean
     *
     * @param <T> T
     * @param clazz class
     * @param name beanId
     * @return T
     */
    public static <T> T getBeanByName(Class<T> clazz, String name) {
        try {
            return ac.getBean(name, clazz);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据beanId获取bean
     *
     * @param name beanId
     * @return Object
     */
    public static Object getBean(String name) {
        return ac.getBean(name);
    }

    /**
     * 根据类型返回bean
     *
     * @param <T> T
     * @param clazz class
     * @return T
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        return ac.getBeansOfType(clazz);
    }

    /**
     * 根据类型返回所有的beanId
     *
     * @param <T> class
     * @param clazz 类型
     * @return T
     * @throws Exception
     */
    public static <T> String[] getBeanNamesForType(Class<T> clazz) {
        return ac.getBeanNamesForType(clazz);
    }

}
